# -*- coding: utf-8 -*-

import pygame, gtk, pygtk
from Principal import Principal

class widget():  
        def __init__(self):
            self.pack = {}
            self.rend = {}
            self.link = {}
            self.ID_num = 0
            self.ID_key = ''
            self.ID_max = 0
            
       
        def Add(self,Type,name,x,y,w,h,Text = '',Size = 18):
            if self.ID_max == 0:
                self.ID_key = name
                IDfocus = True
            else:
                IDfocus = False
           
            #  backgound      border       hilight    Text    selected
            color = [(0,130,0),(125,125,125),(0,220,0),(0,0,0),(0,130,0)]
            #   show  mouse focus
            self.pack[name] = [Type,(x,y),(w,h),color,[False,False,IDfocus],
                               self.ID_max]

            self.Render(name,Text,Size,1)
            self.ID_max += 1

        def AddMenu(self,name,Menu,x,y,Size = 25):
            if self.ID_max == 0:
                self.ID_key = name
                IDfocus = True
            else:
                IDfocus = False
              #  backgound      border       hilight    Text    selected
            color = [(0,130,0),(125,125,125),(0,220,0),(0,0,0),(0,130,0)]

            self.pack[name] = ['menu',(x,y),(0,0),color,[False,False,IDfocus],
                               self.ID_max,len(Menu),0,0]
           
            self.ID_max += 1

            self.RendMenu(name,Menu,Size)

        def RendMenu(self,key,Menu,txtsize):
            Font = pygame.font.Font(None,txtsize)
            self.pack[key][6] = len(Menu)
           
            x,y = self.pack[key][1]
           
            loop = 0
            width = self.pack[key][2][1]
            for mn in Menu:
                size = Font.size(mn)
                if size[0] > width:
                    width = size[0]
                pos = (x - size[0]/2 , y - len(Menu)*txtsize/2 + loop*txtsize)
                Rect = pygame.Rect(pos,size)
               
                NormTxt = Font.render(mn,1,self.pack[key][3][0])
                HiTxt = Font.render(mn,1,self.pack[key][3][2])
                OffTxt = Font.render(mn,1,self.pack[key][3][1])
                SelTxt = Font.render(mn,1,self.pack[key][3][4])

                if loop == 0:
                    self.rend[key] = [(OffTxt,NormTxt,HiTxt,SelTxt,pos,Rect,loop)]
                else:
                    self.rend[key].append((OffTxt,NormTxt,HiTxt,SelTxt,pos,Rect,loop))
                loop += 1

            height = len(Menu)*txtsize
            self.pack[key][2] = (width,height)
           
        def Render(self,key,text,txtsize,curpos):
            Rect = pygame.Rect(self.pack[key][1],self.pack[key][2])
            Font = pygame.font.Font(None,txtsize)
           
            size = Font.size(text)
            x,y = self.pack[key][1]
            w,h = self.pack[key][2]
            rtxt = text
           
            if self.pack[key][0] == 'button':
                pos = (x +((w -size[0])/2),y +((h - size[1])/2))
               

        def SetColor(self,key,code,color):
            # code = 0 - 4
            self.pack[key][3][code] = color

        def SetLink(self,key,Link,var1 = None,var2 = None,Append = False):
            if Append == False:
                self.link[key] = [(Link,var1,var2)]
            else:
                self.link[key].append((Link,var1,var2))

        def DoLink(self,code = 0):
            lk = self.link[self.ID_key]
            if not lk[code][2] == None:
                lk[code][0](lk[code][1],lk[code][2])
            elif not lk[0][1] == None:
                lk[code][0](lk[code][1])
            else:
                lk[code][0]()

        def Draw(self,key,canvas):

                if self.pack[key][0] == 'menu':
                        if self.pack[key][4][2] == True:
                            xcolor = 1
                            peek = 2
                        elif self.pack[key][4][1] == True:
                            xcolor = 2
                            peek = 1
                        else:
                            xcolor = 0
                            peek = 0
                for num in range(0,self.pack[key][6]):
                    if self.pack[key][7] == num:
                        canvas.blit(self.rend[key][num][3],
                                    self.rend[key][num][4])
                    elif self.pack[key][8] == num:
                        canvas.blit(self.rend[key][num][peek],
                                    self.rend[key][num][4])
                    else:
                        canvas.blit(self.rend[key][num][xcolor],
                                    self.rend[key][num][4])

        def MouseOver(self,evt):
            Keys = self.pack.keys()
            x,y = evt.pos
            for key in Keys:
                kx , ky = self.pack[key][1]
                kw , kh = self.pack[key][2]
                if self.pack[key][0] == 'menu':
                    kx -= kw/2
                    ky -= kh/2

                if x > kx and x < kx + kw:
                    if y > ky and y < ky + kh:
                        self.pack[key][4][1] = True
                        if self.pack[key][0] == 'menu':
                            for mn in self.rend[key]:
                                rr = mn[5]
                                if x > rr[0] and x < rr[0] + rr[2]:
                                    if y > rr[1] and y < rr[1] + rr[3]:
                                        self.pack[key][8] = mn[6]
                    else:
                        self.pack[key][4][1] = False
                else:
                    self.pack[key][4][1] = False

        def MouseSelect(self,evt):
            if evt.button == 1:
                Keys = self.pack.keys()
                x,y = evt.pos
                for key in Keys:
                    kx , ky = self.pack[key][1]
                    kw , kh = self.pack[key][2]
                    if self.pack[key][0] == 'menu':
                        kx -= kw/2
                        ky -= kh/2

                    if x > kx and x < kx + kw:
                        if y > ky and y < ky + kh:
                            self.SetFocus(self.pack[key][5])
                            if self.pack[self.ID_key][0] == 'button':
                                self.DoLink()
                            elif self.pack[key][0] == 'menu':
                                for mn in self.rend[key]:
                                    rr = mn[5]
                                    if x > rr[0] and x < rr[0] + rr[2]:
                                        if y > rr[1] and y < rr[1] + rr[3]:
                                            self.pack[key][7] = mn[6]
                                            self.DoLink(self.pack[key][7])
               
        def Event(self,evt):
            if evt.type == pygame.KEYDOWN:
                if evt.key == pygame.K_TAB:
                    self.ID_num += 1
                    self.ID_num %= self.ID_max
                    self.SetFocus(self.ID_num)

                elif self.pack[self.ID_key][0] == 'menu':
                    if evt.key == pygame.K_UP:
                        self.pack[self.ID_key][8] -= 1
                        if self.pack[self.ID_key][8] < 0:
                            self.pack[self.ID_key][8] = self.pack[self.ID_key][6] -1
                    elif evt.key == pygame.K_DOWN:
                        self.pack[self.ID_key][8] += 1
                        self.pack[self.ID_key][8] %= self.pack[self.ID_key][6]
                    elif evt.key == pygame.K_RETURN:
                        self.pack[self.ID_key][7] = self.pack[self.ID_key][8]
                        self.DoLink(self.pack[self.ID_key][7])
                   
            elif evt.type == pygame.MOUSEBUTTONDOWN:
                self.MouseSelect(evt)
           
            elif evt.type == pygame.MOUSEMOTION:
                self.MouseOver(evt)

        def Update(self,canvas):
            Keys = self.pack.keys()
            for key in Keys:
                self.Draw(key,canvas)

        def key_event(self,key,evt):
            letter = None
            if evt.key == pygame.K_BACKSPACE:
                Tx,cr = self.rend[key][0] , self.rend[key][5][0]
                Tx = Tx[:cr-2] + Tx[cr-1:]
                cr -= 1
                if cr < 1:
                    cr = 1
                self.Render(key,Tx,self.rend[key][5][1],cr)

            if evt.key == pygame.K_DELETE:
                self.Render(key,'',self.rend[key][5][1],1)

            if evt.key > 96 and evt.key < 123:
                letter = chr(evt.key)

            if evt.key > 47 and evt.key < 58:
                letter = chr(evt.key)

            if evt.key == pygame.K_SPACE:
                letter = " "

            if not letter == None:
                Tx,cr = self.rend[key][0] , self.rend[key][5][0]
                Tx = Tx[:cr-1] + letter + Tx[cr-1:]
                cr += 1   
                self.Render(key,Tx,self.rend[key][5][1],cr)
                                                     
        def SetFocus(self,ID):
            self.ID_num = ID
            Keys = self.pack.keys()
            for key in Keys:
                if ID == self.pack[key][5]:
                    self.pack[key][4][2] = True
                    self.ID_key = key
                else:
                    self.pack[key][4][2] = False                                                 

def Quit(txt):
        pygame.display.quit()
        exit()

def menutouch(txt):
        objStart = Principal()
        objStart.show()
        objStart.__init__()
        pygame.init()     

if __name__ == "__main__":
        width , height = 1308, 710
        clock = pygame.time.Clock()
        pygame.init()
        screen = pygame.display.set_mode((width,height))

        item = widget()
        item.AddMenu('mn1',['','Start','Option','Quit'],645,280)
        item.SetLink('mn1',menutouch,'')
        item.SetLink('mn1',menutouch,'Option',None,True)
        item.SetLink('mn1',menutouch,'Start',None,True)
        item.SetLink('mn1',Quit,'Quit',None,True)

        Font = pygame.font.Font(None,20)
        Text5 = Font.render("",1,(0,255,0))

        Run = True
        while Run:
            screen.fill((0,150,250))
            mapa = pygame.image.load("menu.png")
            #resize background
            mapa = pygame.transform.scale(mapa, (width, height))
 
            #posição do fundo da tela
            mapPosition = (0, 0)
        
            screen.blit(mapa, mapPosition)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    Run = False
                item.Event(event)

            item.Update(screen)

            
            screen.blit(Text5,(250,200))
           
            pygame.display.flip()
            clock.tick(15)
        Quit('')